import java.io.*;
import java.util.ArrayList;
import java.util.List;

// 账户管理类
public class accountManager {
    private String fileName; // 保存账户信息的文件

    // 构造方法
    public accountManager(String fileName) {
        this.fileName = fileName;
    }

    // 保存账户列表到文件
    public void save(List<Account> list) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName))) {
            oos.writeObject(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 从文件读取账户列表
    private List<Account> loadAccounts() {
        List<Account> accounts = new ArrayList<>();
        File file = new File(fileName);
        if (file.exists()) {
            try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {
                accounts = (List<Account>) ois.readObject();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return accounts;
    }

    // 根据姓名获取账户信息
    public Account get(String name) {
        List<Account> accounts = loadAccounts();
        for (Account account : accounts) {
            if (account.getName().equals(name)) {
                return account;
            }
        }
        return null;
    }

    // 显示所有账户信息
    public void showAll() {
        List<Account> accounts = loadAccounts();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    // 添加新账户
    public void add(Account account) {
        List<Account> accounts = loadAccounts();
        accounts.add(account);
        save(accounts);
    }

    // 主方法，测试账户管理功能
    public static void main(String[] args) {
        accountManager manager = new accountManager("accounts.dat");

        // 添加测试账户
        manager.add(new Account("20160001", "孙悟空", 12900));
        manager.add(new Account("20160002", "猪八戒", 23519));
        manager.add(new Account("20160003", "沙和尚", 6789));

        // 显示所有账户
        System.out.println("所有账户信息：");
        manager.showAll();

        // 根据姓名查询账户
        System.out.println("\n查询孙悟空的账户信息：");
        Account account = manager.get("孙悟空");
        if (account != null) {
            System.out.println(account);
        } else {
            System.out.println("未找到该账户！");
        }
    }
}    